package com.zjz.demo.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2021/10/10/11:59
 * @Description:
 * @Target:
 */

// 自旋锁
public class SpinLockDemo {
    // CAS
    // 不写参数,默认null  数值 0
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    //加锁

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+" ===>mylock");
        // 自旋锁
        while (atomicReference.compareAndSet(null,thread)){

        }
    }

    // 解锁
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+" ===>myUnlock");
        // 自旋锁
        atomicReference.compareAndSet(thread,null);
    }

}
